package com.rt.system.service.impl;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.github.dadiyang.equator.FieldInfo;
import com.github.dadiyang.equator.GetterBaseEquator;
import com.rt.common.exception.ServiceException;
import com.rt.common.utils.DateUtils;
import com.rt.common.utils.StringUtils;
import com.rt.common.utils.file.ImageUtils;
import com.rt.system.domain.*;
import com.rt.system.mapper.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.rt.system.service.IRtQuestionsInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 试题Service业务层处理
 * 
 * @author Yg
 * @date 2022-04-13
 */
@Service
public class RtQuestionsInfoServiceImpl implements IRtQuestionsInfoService 
{
    @Autowired
    private RtQuestionsInfoMapper rtQuestionsInfoMapper;

    @Autowired
    private RtQuestionHistoryMapper rtQuestionHistoryMapper;

    @Autowired
    private RtOptionsInfoMapper rtOptionsInfoMapper;

    @Autowired
    private RtAnswerDataMapper rtAnswerDataMapper;

    @Autowired
    private RtDifficultyMapper rtDifficultyMapper;

    @Autowired
    private RtDifficultyLogDetailMapper rtDifficultyLogDetailMapper;

    @Autowired
    private RtDifficultyLogMainMapper rtDifficultyLogMainMapper;

    @Autowired
    private RtSubjectMapper rtSubjectMapper;

    // 单选
    @Value("${options.radio}")
    private Long radio;

    // 多选
    @Value("${options.check}")
    private Long check;

    // 填空
    @Value("${options.completion}")
    private Long completion;

    // 判断
    @Value("${options.judge}")
    private Long judge;

    // 案列
    @Value("${options.example}")
    private Long example;

    // 简答
    @Value("${options.answer}")
    private Long answer;

    /**
     * 查询试题
     * 
     * @param id 试题主键
     * @return 试题
     */
    @Override
    public RtQuestionsInfo selectRtQuestionsInfoById(String id)
    {
        RtQuestionsInfo rtQuestionsInfo = rtQuestionsInfoMapper.selectRtQuestionsInfoById(id);
        // 判空
        if (StringUtils.isNull(rtQuestionsInfo))return null;
        // 如果是案例题
        if (rtQuestionsInfo.getQuestionTypeId().equals(example)){
            // 查询案例题下的小题
            List<RtQuestionsInfo> rtQuestionsInfos = rtQuestionsInfoMapper.selectRtQuestionsInfoByPId(rtQuestionsInfo.getId());
            // 填空题需要处理
            for (RtQuestionsInfo questionsInfo : rtQuestionsInfos) {
                if (questionsInfo.getQuestionTypeId()==completion){
                    repair(questionsInfo);
                }
            }
            rtQuestionsInfo.setRtQuestionsInfos(rtQuestionsInfos);
        }
        // 如果是填空题
        if (rtQuestionsInfo.getQuestionTypeId()==completion){
            repair(rtQuestionsInfo);
        }
        return rtQuestionsInfo;
    }

    // 填空题
    public void repair(RtQuestionsInfo rtQuestionsInfo){
        String[] split = rtQuestionsInfo.getAnswer().substring(1,rtQuestionsInfo.getAnswer().length()-1).split("\"(,*?)\"");
        List<RtOptionsInfo> optionsList = new ArrayList<>();
        for (String s : split) {
            RtOptionsInfo rtOptionsInfo = new RtOptionsInfo();
            rtOptionsInfo.setRemark(s);
            optionsList.add(rtOptionsInfo);
        }
        rtQuestionsInfo.setRtOptionsInfos(optionsList);
    }

    /**
     * 查询试题列表
     * 
     * @param rtQuestionsInfo 试题
     * @return 试题
     */
    @Override
    public List<RtQuestionsInfo> selectRtQuestionsInfoList(RtQuestionsInfo rtQuestionsInfo)
    {
        return rtQuestionsInfoMapper.selectRtQuestionsInfoList(rtQuestionsInfo);
    }

    /**
     * 新增试题
     * 
     * @param rtQuestionsInfo 试题
     * @return 结果
     */
    @Override
    public int insertRtQuestionsInfo(RtQuestionsInfo rtQuestionsInfo){
        // 时间类型赋值
        rtQuestionsInfo.setCreateTime(DateUtils.getNowDate());
        choose(rtQuestionsInfo,"新增");
        // 根据类型判断
        if(rtQuestionsInfo.getQuestionTypeId().equals(example)){
            // 先新增案例题
            rtQuestionsInfoMapper.insertRtQuestionsInfo(rtQuestionsInfo);
            for (RtQuestionsInfo questionsInfo : rtQuestionsInfo.getRtQuestionsInfos()) {
                questionsInfo.setCreateTime(DateUtils.getNowDate());
                questionsInfo.setParentId(rtQuestionsInfo.getId());
                choose(questionsInfo,"新增");
            }
        }
        // 日志表记录
        return RtQuestionsLog("新增",rtQuestionsInfo.getCreateOperator(),rtQuestionsInfo.getId(),"-","新增id："+rtQuestionsInfo.getId()+",新增题干："+rtQuestionsInfo.getQuestionsContent());
    }

    /**
     * 修改试题
     * 
     * @param rtQuestionsInfo 试题
     * @return 结果
     */
    @Override
    public int updateRtQuestionsInfo(RtQuestionsInfo rtQuestionsInfo)
    {
        // 保存修改前记录
        RtQuestionsInfo questionBeforeList = this.selectRtQuestionsInfoById(rtQuestionsInfo.getId());
        // 修改试题表
        rtQuestionsInfo.setUpdateTime(DateUtils.getNowDate());
        choose(rtQuestionsInfo,"修改");
        // 根据类型判断
        if(rtQuestionsInfo.getQuestionTypeId().equals(example)){
            // 修改基础数据
            rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
            // 根据pid删除案列下的
            rtQuestionsInfoMapper.deleteRtQuestionsInfoByPId(rtQuestionsInfo.getId());
            for (RtQuestionsInfo questionsInfo : rtQuestionsInfo.getRtQuestionsInfos()) {
                questionsInfo.setParentId(rtQuestionsInfo.getId());
                questionsInfo.setCreateTime(DateUtils.getNowDate());
                choose(questionsInfo,"新增");
            }
        }
        // 记录修改后记录
        RtQuestionsInfo questionAfterList = this.selectRtQuestionsInfoById(rtQuestionsInfo.getId());
        // 对象比较
        Map<String,String> compared = compared(questionBeforeList, questionAfterList);
        return RtQuestionsLog("修改",rtQuestionsInfo.getUpdateOperator(),rtQuestionsInfo.getId(),compared.get("questionBefore"),compared.get("questionAfter"));
    }

    /**
     * 批量删除试题
     * 
     * @param ids 需要删除的试题主键
     * @return 结果
     */
    @Override
    public int deleteRtQuestionsInfoByIds(String[] ids)
    {
        return rtQuestionsInfoMapper.deleteRtQuestionsInfoByIds(ids);
    }

    /**
     * 删除试题信息
     * 
     * @param id 试题主键
     * @return 结果
     */
    @Override
    public int deleteRtQuestionsInfoById(String id,String operName)
    {
        // 案例题需根据pid删除
        rtQuestionsInfoMapper.deleteRtQuestionsInfoByPId(id);
        // 删除选项
        rtOptionsInfoMapper.deleteRtOptionsInfoByQuestionId(id);
        // 日志记录
        RtQuestionsLog("删除",operName,id,"-","删除id："+id+",删除题干："+this.selectRtQuestionsInfoById(id).getQuestionsContent());
        return rtQuestionsInfoMapper.deleteRtQuestionsInfoById(id);
    }

    /**
     * 调整难易度
     *
     * @param userName 操作人
     * @return 结果
     */
    @Override
    public int editDifficulty(String userName) {
        // 先查询作答结果
        List<RtAnswerData> rtAnswerData=rtAnswerDataMapper.selectRtAnswerDataErrorList();
        Long count=0L;
        for (RtAnswerData rtAnswerDatum : rtAnswerData) {
            // 根据作答结果查询出难度
            Integer id=rtDifficultyMapper.selectRtDifficultyByError(rtAnswerDatum.getError());
            // 查询原本的试题难度
            RtQuestionsInfo rtQuestionsInfo = rtQuestionsInfoMapper.selectRtQuestionsInfoErrorById(rtAnswerDatum.getQuestionId());
            // 如果不相等说明需要更改难易度
            if (StringUtils.isNotNull(rtQuestionsInfo)&&!id.equals(rtQuestionsInfo.getDifficulty())){
                //新增难易度日志记录表
                RtDifficultyLogDetail rtDifficultyLogDetail = new RtDifficultyLogDetail();
                rtDifficultyLogDetail.setQuestionId(rtAnswerDatum.getQuestionId());
                rtDifficultyLogDetail.setDifficultyBefore(rtQuestionsInfo.getDifficulty());
                rtDifficultyLogDetail.setDifficultyAfter(id);
                rtDifficultyLogDetail.setNewErrorRate(rtAnswerDatum.getError());
                rtDifficultyLogDetail.setUpdateOperator(userName);
                rtDifficultyLogDetailMapper.insertRtDifficultyLogDetail(rtDifficultyLogDetail);
                // 新增试题日志表
                RtQuestionsLog("试题难易度调整",userName,rtAnswerDatum.getQuestionId(),rtDifficultyMapper.selectDifficultyById(rtQuestionsInfo.getDifficulty()),rtDifficultyMapper.selectDifficultyById(id));
                // 修改难度
                rtQuestionsInfo.setDifficulty(id);
                rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
                count++;
            }
        }
        // 新增日志记录大表
        RtDifficultyLogMain rtDifficultyLogMain = new RtDifficultyLogMain();
        rtDifficultyLogMain.setUpdateOperator(userName);
        rtDifficultyLogMain.setUpdateNum(count);
        return rtDifficultyLogMainMapper.insertRtDifficultyLogMain(rtDifficultyLogMain);
    }

    @Override
    public int updateRtQuestionsInfoStatus(RtQuestionsInfo rtQuestionsInfo) {
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        // 保存修改前记录
        RtQuestionsInfo questionBeforeList = this.selectRtQuestionsInfoById(rtQuestionsInfo.getId());
        // 修改试题表
        rtQuestionsInfo.setUpdateTime(DateUtils.getNowDate());
        rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
        // 记录修改后记录
        RtQuestionsInfo questionAfterList = this.selectRtQuestionsInfoById(rtQuestionsInfo.getId());
        return RtQuestionsLog("修改使用状态",rtQuestionsInfo.getUpdateOperator(),rtQuestionsInfo.getId(),"状态:"+getUseStatus(questionBeforeList.getUseStatus())+",解封日期:"+(StringUtils.isNull(questionBeforeList.getLockEndTime()) ? "": format.format(questionBeforeList.getLockEndTime())),"状态:"+getUseStatus(questionAfterList.getUseStatus())+",解封日期:"+(StringUtils.isNull(questionAfterList.getLockEndTime()) ? "": format.format(questionAfterList.getLockEndTime())));
    }
    // 获取使用状态
    public String getUseStatus(Integer status) {
        if (status==0){
            return "激活期";
        }else if (status==1){
            return "封存期";
        }
        return "待删除";
    }

    @Override
    public int updateRtQuestionsInfoVerityStatus(RtQuestionsInfo rtQuestionsInfo) {
        // 修改试题表
        rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
        // 记录修改后记录
        return RtQuestionsLog("审核",rtQuestionsInfo.getUpdateOperator(),rtQuestionsInfo.getId(),rtQuestionsInfo.getId()+"待审核",rtQuestionsInfo.getId()+"审核通过");
    }

    @Override
    public List<RtQuestionsInfo> selectRtQuestionsInfoCountList(RtQuestionsInfo rtQuestionsInfo) {
        return rtQuestionsInfoMapper.selectRtQuestionsInfoCountList(rtQuestionsInfo);
    }


    // 单选多选 填空
    public void choose(RtQuestionsInfo rtQuestionsInfo,String operType){
        // 根据类型判断
        if (rtQuestionsInfo.getQuestionTypeId().equals(radio) || rtQuestionsInfo.getQuestionTypeId().equals(check)){
            check(rtQuestionsInfo,operType);
        }else if (rtQuestionsInfo.getQuestionTypeId().equals(completion)){
            completion(rtQuestionsInfo,operType);
        }else if (rtQuestionsInfo.getQuestionTypeId().equals(judge) || rtQuestionsInfo.getQuestionTypeId().equals(answer)) {
            if (operType.equals("新增")){
                rtQuestionsInfoMapper.insertRtQuestionsInfo(rtQuestionsInfo);
            }else {
                rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
            }
            // 保存二进制流
            RtQuestionsPhoto(rtQuestionsInfo);
        }
    }

    // 填空
    public void completion(RtQuestionsInfo rtQuestionsInfo,String operType){
        StringBuffer stringBuffer=new StringBuffer();
        for (RtOptionsInfo rtOptionsInfo : rtQuestionsInfo.getRtOptionsInfos()) {
            stringBuffer.append('"'+rtOptionsInfo.getRemark()+'"').append(',');
            rtQuestionsInfo.setAnswer(stringBuffer.toString().substring(0, stringBuffer.length() - 1));
        }
        // 新增试题表
        if (operType.equals("新增")){
            rtQuestionsInfoMapper.insertRtQuestionsInfo(rtQuestionsInfo);
        }else {
            rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
        }
        // 保存二进制流
        RtQuestionsPhoto(rtQuestionsInfo);
    }

    // 单选与多选
    public void check(RtQuestionsInfo rtQuestionsInfo,String operType){
        // 新增或试题表
        if (operType.equals("新增")){
            rtQuestionsInfoMapper.insertRtQuestionsInfo(rtQuestionsInfo);
        }else {
            rtQuestionsInfoMapper.updateRtQuestionsInfo(rtQuestionsInfo);
        }
        // 保存二进制流
        RtQuestionsPhoto(rtQuestionsInfo);
        // 先删除原有选项
        rtOptionsInfoMapper.deleteRtOptionsInfoByQuestionId(rtQuestionsInfo.getId());
        // 新增选项表
        for (RtOptionsInfo rtOptionsInfo : rtQuestionsInfo.getRtOptionsInfos()) {
            rtOptionsInfo.setQuestionId(rtQuestionsInfo.getId());
            rtOptionsInfo.setCreateTime(DateUtils.getNowDate());
            rtOptionsInfo.setCreateOperator(rtQuestionsInfo.getCreateOperator());
            // 新增试题表
            rtOptionsInfoMapper.insertRtOptionsInfo(rtOptionsInfo);
        }
    }
    /**
     * 试题日志
     *
     * @param operType 操作类型
     * @param operName 操作人
     * @param questionId 试题id
     * @param questionAfter   前
     * @return 结果
     */
    public Integer RtQuestionsLog(String operType,String operName,String questionId,String questionBefore,String questionAfter){
        RtQuestionHistory rtQuestionHistory = new RtQuestionHistory();
        rtQuestionHistory.setOperType(operType);
        rtQuestionHistory.setOperName(operName);
        rtQuestionHistory.setQuestionId(questionId);
        rtQuestionHistory.setQuestionAfter(questionAfter);
        rtQuestionHistory.setQuestionBefore(questionBefore);
        rtQuestionHistory.setOperTime(DateUtils.getNowDate());
        if (questionAfter==questionBefore){
            return 1;
        }
        return rtQuestionHistoryMapper.insertRtQuestionHistory(rtQuestionHistory);
    }

    // 保存二进制流
    public void RtQuestionsPhoto(RtQuestionsInfo rtQuestionsInfo){
        // 先删除原本的数据
        rtQuestionsInfoMapper.deleteRtQuestionsPhotoQId(rtQuestionsInfo.getId());
        List<String> imgStr = getImgStr(rtQuestionsInfo.getQuestionsContent());
        if (StringUtils.isNotNull(imgStr)){
            try {
                for (String img : imgStr) {
//                   byte[] imageBinary = getImageBinary(RtConfig.getProfile() + img.substring(16));
                    byte[] image = ImageUtils.readFile(img);
                    Map<String, Object> map = new HashMap<>();
                    map.put("attachment",image);
                    map.put("questionId",rtQuestionsInfo.getId());
                    rtQuestionsInfoMapper.insertRtQuestionsPhoto(map);
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    // 对象比较
    public Map compared(RtQuestionsInfo questionBeforeList,RtQuestionsInfo  questionAfterList) {
        // 记录字段
        String questionBefore="";
        String questionAfter="";
        GetterBaseEquator getterBaseEquator = new GetterBaseEquator();
        List<FieldInfo> diffFields = getterBaseEquator.getDiffFields(questionBeforeList, questionAfterList);
        for (FieldInfo diffField : diffFields) {
            questionBefore+=diffField.getFieldName()+":"+diffField.getFirstVal()+",";
            questionAfter+=diffField.getFieldName()+":"+diffField.getSecondVal()+",";
        }
        Map<String, String> map = new HashMap<>();
        map.put("questionBefore",questionBefore);
        map.put("questionAfter",questionAfter);
        return map;
    }

    // 图片路径
    public static List<String> getImgStr(String htmlStr) {
        List<String> list = new ArrayList<>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        // String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                list.add(m.group(1));
            }
        }
        return list;
    }
    /**
     * 图片转换为二进制流
     * @param imgSrc 图片本地地址
     * @return 返回图片转换后的二进制流（类型：String）
     * @return 若转换失败返回 null
     *
     * */
    public static byte[] getImageBinary(String imgSrc) throws Exception {

        FileInputStream fin = new FileInputStream(new File(imgSrc));
        //可能溢出,简单起见就不考虑太多,如果太大就要另外想办法，比如一次传入固定长度byte[]
        byte[] bytes  = new byte[1000000];
        fin.read(bytes);

        String baseStr= Base64.getEncoder().encodeToString(bytes);
        // 导出
        byte[] op= Base64.getDecoder().decode(baseStr);
        FileOutputStream fos = new FileOutputStream(new File("D:\\1.jpg"));
        fos.write(op,0,op.length);
        fos.flush();
        fos.close();

//        File f = new File(imgSrc);
//        BufferedImage bi;
//        try {
//            bi = ImageIO.read(f);
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            ImageIO.write(bi, "jpg", baos);  //经测试转换的图片是格式这里就什么格式，否则会失真
//            byte[] bytes = baos.toByteArray();
//            return bytes;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
        return op;
    }

    /**
     * word 导入
     *
     * @param file
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(MultipartFile file,Long userId,String userName) throws IOException {
        InputStream is = file.getInputStream();
        HWPFDocument doc=new HWPFDocument(is);
        RtQuestionsInfo rtQuestionsInfo = new RtQuestionsInfo();
        ArrayList<RtOptionsInfo> optionsInfos = new ArrayList<>();
        Integer sum=0;
        Range range = doc.getRange();
        for (int i = 0; i < range.numParagraphs(); i++) {
            try {
                if (range.getParagraph(i).text()!=null && range.getParagraph(i).text()!=""){
                    if (range.getParagraph(i).text().contains("科目:")) {
                        rtQuestionsInfo.setSubjectId(rtSubjectMapper.selectSubjectByName(cut(range, i,":")));
                        if (rtQuestionsInfo.getSubjectId()==null)throw new ServiceException("导入失败,请检查数据");
                    }
                    if (range.getParagraph(i).text().contains("命题人:")) {
                        rtQuestionsInfo.setExpertName(rtQuestionsInfoMapper.selectExpertName(cut(range, i,":")));
                        if (rtQuestionsInfo.getExpertName()==null)throw new ServiceException("导入失败,请检查数据");
                    }
                    if (range.getParagraph(i).text().contains("试题类型:")) {
                        rtQuestionsInfo.setQuestionTypeId(rtQuestionsInfoMapper.selectQuestionTypeByName(cut(range, i,":")));
                        if (rtQuestionsInfo.getQuestionTypeId()==null)throw new ServiceException("导入失败,请检查数据");
                    }
                    if (range.getParagraph(i).text().contains("知识点编码:")) {
                        rtQuestionsInfo.setKnowledgeId(rtQuestionsInfoMapper.selectKnowledgeByName(cut(range, i,":"),rtQuestionsInfo.getSubjectId()));
                        rtQuestionsInfo.setImportanceId(rtQuestionsInfoMapper.selectImportanceByCode(cut(range, i,":")));
                        if (rtQuestionsInfo.getKnowledgeId()==null)throw new ServiceException("导入失败,请检查数据");
                    }
                    if (range.getParagraph(i).text().contains("错误率:")) {
                        rtQuestionsInfo.setDifficulty(rtQuestionsInfoMapper.selectDifficultyByName(cut(range, i,":")));
                        if (rtQuestionsInfo.getDifficulty()==null)throw new ServiceException("导入失败,请检查数据");
                    }
                    if (range.getParagraph(i).text().contains("题干:")){
                        rtQuestionsInfo.setQuestionsContent(cut(range, i,":"));
                        if (rtQuestionsInfo.getQuestionsContent()==null)throw new ServiceException("导入失败,请检查数据");
                    }
                    if (range.getParagraph(i).text().contains("题数:")){
                        sum=Integer.valueOf(cut(range, i,":"));
                    }
                    if (range.getParagraph(i).text().contains("答案:")){
                        switch (rtQuestionsInfo.getQuestionTypeId().intValue()){
                            case 1:
                            case 2:
                                // 将选项表添加进去
                                rtQuestionsInfo.setRtOptionsInfos(optionsInfos);
                                // 获取选项转为对应的数字
                                for (String answer : cut(range, i,":").split(",")) {
                                    // 选中的选项
                                    rtQuestionsInfo.getRtOptionsInfos().get(letterToNumber(answer)-1).setIsAnswer(1);
                                }
                                break;
                            case 4:
                                if (cut(range, i,":").equals("对")){
                                    rtQuestionsInfo.setIsCorrect(1);
                                }else if (cut(range, i,":").equals("错")){
                                    rtQuestionsInfo.setIsCorrect(0);
                                }
                                break;
                            case 6:
                                rtQuestionsInfo.setAnswer(cut(range, i,":"));
                                break;
                        }
                    }
                    // 选项数据添加
                    if (range.getParagraph(i).text().contains("、")){
                        RtOptionsInfo rtOptionsInfo = new RtOptionsInfo();
                        rtOptionsInfo.setRemark(cut(range, i, "、"));
                        rtOptionsInfo.setIsAnswer(0);
                        optionsInfos.add(rtOptionsInfo);
                    }
                    if (range.getParagraph(i).text().contains("====================")){
                        rtQuestionsInfo.setUserId(userId);
                        rtQuestionsInfo.setCreateOperator(userName);
                        // 先提交上个题目
                        // 案例题
                        if (rtQuestionsInfo.getQuestionTypeId()==example){
                            rtQuestionsInfoMapper.insertRtQuestionsInfo(rtQuestionsInfo);
                            rtQuestionsInfo.setParentId(rtQuestionsInfo.getId());
                        }else {
                            this.insertRtQuestionsInfo(rtQuestionsInfo);
                        }
                        // pid重置
                        if (sum!=0)sum--;else rtQuestionsInfo.setParentId(null);
                        // 重置参数
                        reset(rtQuestionsInfo,optionsInfos);
                    }
                }
            }catch (Exception e){
                System.out.println(e);
                throw new ServiceException("很抱歉，导入失败！请检查数据！");
            }finally {
                closeStream(is);
            }
        }
        return "恭喜您，数据已全部导入成功！";
    }

    /**
     * 关闭输入流
     *
     * @param is
     */
    private static void closeStream(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 字符串切割
     *
     */
    private static String cut(Range range,int i,String split) {
        int index=range.getParagraph(i).text().indexOf(split);
        return range.getParagraph(i).text().substring(index+1).trim();
    }

    /**
     * 字母转为数字
     *
     */
    public int letterToNumber(String letter) {
        int number=0;
        byte[] bytes =letter.toLowerCase().getBytes();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            number=b-96;
        }
        return number;
    }
    /**
     * 重置参数
     *
     */
    public void reset(RtQuestionsInfo rtQuestionsInfo,ArrayList<RtOptionsInfo> optionsInfos) {
        rtQuestionsInfo.setId(null);
        rtQuestionsInfo.setIsCorrect(null);
        rtQuestionsInfo.setQuestionsContent(null);
        rtQuestionsInfo.setAnswer(null);
        rtQuestionsInfo.setRtOptionsInfos(null);
        rtQuestionsInfo.setRtQuestionsInfos(null);
        optionsInfos.clear();
    }

}
